from __future__ import annotations

from dataclasses import dataclass
from math import radians, tan, cos
from typing import List


@dataclass
class JanbuSlice:
    width_m: float
    height_m: float
    unit_weight_kN_m3: float
    cohesion_kPa: float
    friction_deg: float
    base_inclination_deg: float
    pore_pressure_kPa: float = 0.0


@dataclass
class JanbuResult:
    factor_of_safety: float
    iterations: int
    converged: bool
    note: str


def janbu_simplified(slices: List[JanbuSlice], tol: float = 1e-4, max_iter: int = 200) -> JanbuResult:
    """Janbu 简化法：Fs = Σ(c' b + (W - u b) tanφ') / (Σ(W sinα) + Σ((W - u b) tanφ' cosα / Fs))。迭代解 Fs。"""

    def compute(F: float) -> float:
        num = 0.0
        den = 0.0
        add = 0.0
        for s in slices:
            b = s.width_m
            W = s.width_m * s.height_m * s.unit_weight_kN_m3
            alpha = radians(s.base_inclination_deg)
            phi = radians(s.friction_deg)
            u = s.pore_pressure_kPa / 1000.0
            num += s.cohesion_kPa / 1000.0 * b + (W - u * b) * tan(phi)
            den += W * 0.0  # 简化忽略外力
            add += (W - u * b) * tan(phi) * cos(alpha) / max(1e-9, F)
        return num / max(1e-9, den + add)

    F = 1.0
    for it in range(1, max_iter + 1):
        Fn = compute(F)
        if abs(Fn - F) < tol:
            return JanbuResult(Fn, it, True, "Janbu简化收敛")
        F = 0.5 * (F + Fn)
    return JanbuResult(F, max_iter, False, "未收敛")


